<!DOCTYPE html>
<html lang="zh_cn">
<head>
          <title>来玩魔王的咚</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charset="utf-8" />
        <!-- twitter card metadata -->
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/images/mowang.png">
<meta name="twitter:site" content="">
<meta name="twitter:title" content="pytest（五）经典xUnit风格的setup/teardown">
<meta name="twitter:description" content="<p>在Pytest中，也有类似于unittest那样的的xUnit style的setup/teardown。</p>">
        <!-- OG Tags -->
<meta property="og:url" content="/pytest-xunit-style-setup.html"/>
<meta property="og:title" content="来玩魔王的咚 | pytest（五）经典xUnit风格的setup/teardown" />
<meta property="og:description" content="<p>在Pytest中，也有类似于unittest那样的的xUnit style的setup/teardown。</p>" />
        <!-- favicon -->
        <link rel="icon" type="image/png" href="/images/mowang.png">
        <!-- moment.js for date formatting -->
        <script src="/theme/js/moment.js"></script>
        <!-- css -->
        <link rel="stylesheet" type="text/css" href="/theme/css/main.css" />
        <!-- 左边的menu，如果页面高度不够，就跟着滚动，否则文章分类显示不全 -->
        <link rel="stylesheet" type="text/css" href="/theme/css/mycss/menu.css" />
		<script>
			
                /*! grunt-grunticon Stylesheet Loader - v2.1.2 | https://github.com/filamentgroup/grunticon | (c) 2015 Scott Jehl, Filament Group, Inc. | MIT license. */
    
    (function(e){function t(t,n,r,o){"use strict";function a(){for(var e,n=0;u.length>n;n++)u[n].href&&u[n].href.indexOf(t)>-1&&(e=!0);e?i.media=r||"all":setTimeout(a)}var i=e.document.createElement("link"),l=n||e.document.getElementsByTagName("script")[0],u=e.document.styleSheets;return i.rel="stylesheet",i.href=t,i.media="only x",i.onload=o||null,l.parentNode.insertBefore(i,l),a(),i}var n=function(r,o){"use strict";if(r&&3===r.length){var a=e.navigator,i=e.Image,l=!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")||e.opera&&-1===a.userAgent.indexOf("Chrome")||-1!==a.userAgent.indexOf("Series40")),u=new i;u.onerror=function(){n.method="png",n.href=r[2],t(r[2])},u.onload=function(){var e=1===u.width&&1===u.height,a=r[e&&l?0:e?1:2];n.method=e&&l?"svg":e?"datapng":"png",n.href=a,t(a,null,null,o)},u.src="",document.documentElement.className+=" grunticon"}};n.loadCSS=t,e.grunticon=n})(this);(function(e,t){"use strict";var n=t.document,r="grunticon:",o=function(e){if(n.attachEvent?"complete"===n.readyState:"loading"!==n.readyState)e();else{var t=!1;n.addEventListener("readystatechange",function(){t||(t=!0,e())},!1)}},a=function(e){return t.document.querySelector('link[href$="'+e+'"]')},c=function(e){var t,n,o,a,c,i,u={};if(t=e.sheet,!t)return u;n=t.cssRules?t.cssRules:t.rules;for(var l=0;n.length>l;l++)o=n[l].cssText,a=r+n[l].selectorText,c=o.split(");")[0].match(/US\-ASCII\,([^"']+)/),c&&c[1]&&(i=decodeURIComponent(c[1]),u[a]=i);return u},i=function(e){var t,o,a;o="data-grunticon-embed";for(var c in e)if(a=c.slice(r.length),t=n.querySelectorAll(a+"["+o+"]"),t.length)for(var i=0;t.length>i;i++)t[i].innerHTML=e[c],t[i].style.backgroundImage="none",t[i].removeAttribute(o);return t},u=function(t){"svg"===e.method&&o(function(){i(c(a(e.href))),"function"==typeof t&&t()})};e.embedIcons=i,e.getCSS=a,e.getIcons=c,e.ready=o,e.svgLoadedCallback=u,e.embedSVG=u})(grunticon,this);
                
                grunticon(["/theme/css/icons.data.svg.css", "/theme/css/icons.data.png.css", "/theme/css/icons.fallback.css"]);
            </script>
        <noscript><link href="/theme/css/icons.fallback.css" rel="stylesheet"></noscript>
        <!-- menu toggle javascript -->
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", initMenu);
            
            function initMenu(){
                var menu = document.getElementById("menu");
                var menulink = document.getElementById("menu-link");
                menulink.addEventListener("click", function toggleMenu(){
                        window.event.preventDefault();
                        menulink.classList.toggle('active');
                        menu.classList.toggle('active');              
                    });
            };
        </script>
        <!-- 不蒜子 -->
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    <meta name="description" content="<p>在Pytest中，也有类似于unittest那样的的xUnit style的setup/teardown。</p>" />

    <meta name="tags" content="测试" />
  <!-- 替换部分base的样式，看文章时，要再宽一点，右边有很多空间可以撑开 -->
  <link rel="stylesheet" type="text/css" href="/theme/css/mycss/article.css" />

</head>
<body>
    <div role="banner" id="masthead">
        <header>
            <a href="/"><img src="/images/mowang.png" alt="McManus Logo"></a>
                <h1>来玩魔王的咚@骑士救兵</h1>
            <a href="#menu" id="menu-link">more stuff</a>
            <nav id="menu">
                <ul>
                        <li><a href="/tags">tags</a></li>
                            <li><a href="/category/cloud.html">Cloud</a></li>
                            <li><a href="/category/docker.html">Docker</a></li>
                            <li><a href="/category/go.html">Go</a></li>
                            <li><a href="/category/linux.html">Linux</a></li>
                            <li class="active"><a href="/category/python.html">Python</a></li>
                            <li><a href="/category/xue-xi-bi-ji.html">学习笔记</a></li>
                            <li><a href="/category/yun-wei-zi-dong-hua.html">运维自动化</a></li>
                </ul>
            </nav>
        </header>
    </div>
        <div class="page" role="main">
  <div class="article" role="article">
    <article>
        <footer>
            <a name="top"></a>
            <p>
              <time datetime=" 2022-03-24 12:10:00+08:00">
                <script>document.write(moment('2022-03-24 12:10:00+08:00').format('LL'));</script>
              </time>
              ~
              <time datetime=" 2022-03-24 12:10:00+08:00">
                <script>document.write(moment('2022-03-24 14:29:00+08:00').format('LL'));</script>
              </time>
            </p>
        </footer>
        <header>
          <h2>
            pytest（五）经典xUnit风格的setup/teardown
          </h2>
        </header>
      <div class="content">
         <div class="toc">
<ul>
<li><a href="#han-shu-ji-bie">函数级别</a><ul>
<li><a href="#huo-qu-han-shu-shu-xing">获取函数属性</a></li>
</ul>
</li>
<li><a href="#lei-ji-bie">类级别</a></li>
<li><a href="#lei-ce-shi-fang-fa-ji-bie">类测试方法级别</a></li>
<li><a href="#mo-kuai-ji-bie">模块级别</a></li>
<li><a href="#jian-yi-shi-yong-gu-jian">建议使用固件</a></li>
</ul>
</div>
<p>pytest提供了fixture固件的机制，能实现测试前的准备（setup）和测试后的清理工作（teardown）。这里的方法是类似于unittest提供的那种机制。并且提供了四个级别的支持：函数级别、类级别、类测试方法级别、模块级别。<br>
和固件的区别是，会默认将模块、实例方法、函数作为参数传递递给setup/teardown，可以方便的获取这些对象的属性。  </p>
<h3 id="han-shu-ji-bie"><a class="toclink" href="#han-shu-ji-bie">函数级别</a></h3>
<p>直接使用setup_function和teardown_function作为函数名称，这两个函数分别会在每个测试函数之前、之后调用一次：</p>
<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">setup_function</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;in setup function&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">teardown_function</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;in teardown function&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">test_case1</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;in test case 1&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="mi">0</span>

<span class="k">def</span> <span class="nf">test_case2</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;in test case 2&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="mi">0</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">pytest</span>
    <span class="n">pytest</span><span class="o">.</span><span class="n">main</span><span class="p">([</span><span class="vm">__file__</span><span class="p">])</span>

<span class="sd">&#39;&#39;&#39;</span>
<span class="sd">=========================================== test session starts ============================================</span>
<span class="sd">platform win32 -- Python 3.9.0, pytest-7.0.1, pluggy-1.0.0</span>
<span class="sd">rootdir: I:\gitee.com\steeed\pytest-examples</span>
<span class="sd">collected 2 items</span>

<span class="sd">tests\test_function_level.py FF                                                              [100%]</span>

<span class="sd">================================================= FAILURES ================================================= </span>
<span class="sd">________________________________________________ test_case1 ________________________________________________ </span>

<span class="sd">    def test_case1():</span>
<span class="sd">        print(&#39;Test case 1&#39;)</span>
<span class="sd">&gt;       assert 0</span>
<span class="sd">E       assert 0</span>

<span class="sd">tests\test_function_level.py:16: AssertionError</span>
<span class="sd">------------------------------------------ Captured stdout setup ------------------------------------------- </span>
<span class="sd">in setup function</span>
<span class="sd">------------------------------------------- Captured stdout call ------------------------------------------- </span>
<span class="sd">in test case 1</span>
<span class="sd">----------------------------------------- Captured stdout teardown ----------------------------------------- </span>
<span class="sd">in teardown function</span>
<span class="sd">________________________________________________ test_case2 ________________________________________________ </span>

<span class="sd">    def test_case2():</span>
<span class="sd">        print(&#39;test case 2&#39;)</span>
<span class="sd">&gt;       assert 0</span>
<span class="sd">E       assert 0</span>

<span class="sd">tests\test_function_level.py:20: AssertionError</span>
<span class="sd">------------------------------------------ Captured stdout setup ------------------------------------------- </span>
<span class="sd">in setup function</span>
<span class="sd">------------------------------------------- Captured stdout call ------------------------------------------- </span>
<span class="sd">in test case 2</span>
<span class="sd">----------------------------------------- Captured stdout teardown ----------------------------------------- </span>
<span class="sd">in teardown function</span>
<span class="sd">========================================= short test summary info ========================================== </span>
<span class="sd">FAILED tests/test_function_level.py::test_case1 - assert 0</span>
<span class="sd">FAILED tests/test_function_level.py::test_case2 - assert 0</span>
<span class="sd">============================================ 2 failed in 0.09s ============================================= </span>
<span class="sd">&#39;&#39;&#39;</span>
</code></pre></div>

<h4 id="huo-qu-han-shu-shu-xing"><a class="toclink" href="#huo-qu-han-shu-shu-xing">获取函数属性</a></h4>
<p>可以为setup_function/teardown_function传入一个参数，名称可以任意，通常使用function作为参数名称。该参数就是当前的测试函数本身：</p>
<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">setup_function</span><span class="p">(</span><span class="n">function</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;setting up&quot;</span><span class="p">,</span> <span class="n">function</span><span class="p">)</span>         <span class="c1"># 打印函数对象</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;setting up&quot;</span><span class="p">,</span> <span class="n">function</span><span class="o">.</span><span class="vm">__doc__</span><span class="p">)</span> <span class="c1"># 打印函数的doc信息</span>

<span class="k">def</span> <span class="nf">teardown_function</span><span class="p">(</span><span class="n">function</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">test_case</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;test case&quot;&quot;&quot;</span>
    <span class="k">assert</span> <span class="mi">0</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">pytest</span>
    <span class="n">pytest</span><span class="o">.</span><span class="n">main</span><span class="p">([</span><span class="vm">__file__</span><span class="p">])</span>

<span class="sd">&#39;&#39;&#39;</span>
<span class="sd">================================ test session starts ================================</span>
<span class="sd">platform win32 -- Python 3.9.0, pytest-7.0.1, pluggy-1.0.0</span>
<span class="sd">rootdir: I:\gitee.com\steeed\pytest-examples</span>
<span class="sd">collected 1 item                                                                      </span>

<span class="sd">tests\test_function_level2.py F                                 [100%]</span>

<span class="sd">===================================== FAILURES ====================================== </span>
<span class="sd">_____________________________________ test_case _____________________________________ </span>

<span class="sd">    def test_case():</span>
<span class="sd">        &quot;&quot;&quot;test case &quot;&quot;&quot;</span>
<span class="sd">&gt;       assert 0</span>
<span class="sd">E       assert 0</span>

<span class="sd">tests\test_function_level2.py:14: AssertionError</span>
<span class="sd">------------------------------- Captured stdout setup ------------------------------- </span>
<span class="sd">setting up &lt;function test_case at 0x000001F1CA348790&gt;</span>
<span class="sd">setting up test case</span>
<span class="sd">============================== short test summary info ============================== </span>
<span class="sd">FAILED tests/test_function_level2.py::test_case - assert 0</span>
<span class="sd">================================= 1 failed in 0.06s =================================</span>
<span class="sd">&#39;&#39;&#39;</span>
</code></pre></div>

<p>function是可选参数，可以始终加上，不用可以不加。  </p>
<h3 id="lei-ji-bie"><a class="toclink" href="#lei-ji-bie">类级别</a></h3>
<p>在类级别，会在测试类中的第一个测试方法开始前调用setup_class，在最后一个测试方法结束后调用teardown_class。<br>
在测试类的内部，提供setup_class/teardown_class方法。建议加上<code>@classmethod</code>装饰器定义为类方法：</p>
<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">TestCaseOne</span><span class="p">:</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">setup_class</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;in setup class&quot;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">teardown_class</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;in teardown class&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_case1</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;in test case 1&#39;</span><span class="p">)</span>
        <span class="k">assert</span> <span class="mi">0</span>
</code></pre></div>

<p>按照类的习惯用法，不加<code>@classmethod</code>装饰器，默认就是实例的方法，参数名使用self，但是依然是将类传递给参数。所以加不加装饰器都一样，不过还是加上明确为类方法。这里没有可选参数。  </p>
<h3 id="lei-ce-shi-fang-fa-ji-bie"><a class="toclink" href="#lei-ce-shi-fang-fa-ji-bie">类测试方法级别</a></h3>
<p>在测试类中，在每个测试方法调用前后都执行的是setup_method/teardown_method方法。可选参数的名称建议使用method：</p>
<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">TestCaseTwo</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">setup_method</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span> <span class="n">method</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;in setup method&quot;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">method</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">teardown_method</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span> <span class="n">method</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;in teardown method&quot;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">method</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_case2</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;in test case 2&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">assert</span> <span class="mi">0</span>
</code></pre></div>

<p>每个测试函数都会生成一个独立的对象，setup_method/teardown_method中的self参数传入的就是当前测试生成的对象。method参数传入的是这个对象使用的实例方法。  </p>
<h3 id="mo-kuai-ji-bie"><a class="toclink" href="#mo-kuai-ji-bie">模块级别</a></h3>
<p>使用的函数名称是setup_module/teardown_module，可选的参数名称建议是module。模块中的第一个测试用例开始前执行setup_module，模块中的最后一个测试用例结束后运行teardown_module：</p>
<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">setup_module</span><span class="p">(</span><span class="n">module</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot; setup any state specific to the execution of the given module.&quot;&quot;&quot;</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">teardown_module</span><span class="p">(</span><span class="n">module</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;teardown any state that was previously setup with a setup_module</span>
<span class="sd">    method.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">pass</span>
</code></pre></div>

<h3 id="jian-yi-shi-yong-gu-jian"><a class="toclink" href="#jian-yi-shi-yong-gu-jian">建议使用固件</a></h3>
<p>这个风格的用法和unittest类似，很容易理解。如果不需要使用module、method、function这些可选参数的话，可以很容易的通过使用pytest提供的固件来实现同样的效果。<br>
推荐使用强大的<a href="/pytest-fixture.html">Fixture固件</a>执行setup的逻辑，固件中的<a href="/pytest-fixture.html#yield-tui-jian">yield</a>相当于是teardown。  </p>
      </div>
      <div class="back-to-top">
        <a href="/">HOME</a>
        <a href="#top">TOP</a>
      </div>
    </article>
  </div>
<!-- end article -->
<!-- 页面往下滚动一段之后才会显示TOC -->
<script>
  window.onscroll = function() {
    var tocbox = document.getElementsByClassName('toc')[0];
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    var osWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    // console.log(osTop)
    if (osTop>300 && osWidth>865) {
      tocbox.style.display = "block"
    }
    if (osTop<300 || osWidth<865) {
      tocbox.style.display = "none"
    }
  }
</script>
                <footer>
                    <div class="icons">
                    </div>
                    <span id="busuanzi_container_page_pv" style="padding: 10px">本文阅读量<span id="busuanzi_value_page_pv"></span>次</span>
                    <span id="busuanzi_container_site_pv" style="padding: 10px">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
                    <span id="busuanzi_container_site_uv" style="padding: 10px">本站总访客数<span id="busuanzi_value_site_uv"></span>人</span>
                    <p>© <script>document.write(moment().format('YYYY'));</script> 749B</p>
                </footer>
        </div>
</body>
</html>